﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;

namespace Xceed.Silverlight.ListBox
{
  internal class ScalingStopFunction : IScalingFunction
  {
    #region Constructor

    internal ScalingStopFunction()
    {
      ScalingStops = new ObservableCollection<ScalingStop>();
    }

    #endregion

    #region ScalingStops Property

    internal ObservableCollection<ScalingStop> ScalingStops
    {
      get;
      set;
    }

    #endregion

    #region Private Methods

    private double ApplyLinearInterpolation( double x, double x1, double x2, double y1, double y2 )
    {
      double deltaX = x2 - x1;

      Debug.Assert( Math.Abs( deltaX ) >= double.Epsilon );

      double m = ( y2 - y1 ) / deltaX;
      double b = y1 - m * x1;

      return m * x + b;
    }

    #endregion

    #region IScalingFunction Members

    double IScalingFunction.GetScalingFactor( int percentage, bool forcedInViewport, bool isGroupDataItem )
    {
      // We need at least two points to do an interpolation.
      if( this.ScalingStops.Count <= 1 )
        return 1d;

      double offset = ( double )percentage / 100.0d;
      List<ScalingStop> stops = this.ScalingStops.OrderBy( stop => stop.Offset ).ToList();

      ScalingStop start = stops[ 0 ];
      ScalingStop end = stops[ 1 ];

      int count = stops.Count;
      for( int i = 2; i < count; i++ )
      {
        // We have found the two points to use for interpolation or extrapolation.
        if( offset <= end.Offset )
          break;

        start = end;
        end = stops[ i ];
      }

      return this.ApplyLinearInterpolation( start.Offset + ( offset - start.Offset ),
                                            start.Offset,
                                            end.Offset,
                                            start.ScalingFactor,
                                            end.ScalingFactor );
    }

    #endregion
  }
}
